const request = require("../../utils/request.js").request;
const url = require("../../utils/request.js").commonUrl;
const util = require("../../utils/util.js");
const collectUtil = require("../../utils/collect-util.js");
var latitude, longitude, mapCtx;
const app = getApp();
var actyinfo;
var searchWords = [
    {
        id: "01",
        word: "博物馆",
        src: "../../images/home2.png"
    },
    {
        id: "02",
        word: "演出",
        src: "../../images/home3.png"
    },
    {
        id: "03",
        word: "展览",
        src: "../../images/home4.png"
    },
    {
        id: "04",
        word: "游乐园",
        src: "../../images/home5.png"
    },
    {
        id: "05",
        word: "采摘",
        src: "../../images/home6.png"
    }
]

Page({
    data: {
        url: url,
        markers: [],
        latitude: '',
        longitude: '',
        placeData: {},
        windowWidth: "",
        list: [],
        searchWords: searchWords,
        showList: false,
        index: ''
    },
    //点击地图隐藏
    list: function (e) {
        this.setData({
            showList: false,
        })
    },

    detailGo: function (event) {
        let index = event.currentTarget.dataset.itemid;
        let activityId = this.data.list[index].activityId;
        let activityAreaId = this.data.list[index].activityAreaId;
        var detailInfo = {
            activityId: activityId,
            activityAreaId: activityAreaId
        }
        this.setData({
            index: index
        })

        wx.navigateTo({
            url: '../details/details?detailInfo=' + JSON.stringify(detailInfo)
        })
    },


    //收藏活动点
    like: function (event) {
        let that = this;
        util.isLogin(function () {
            let result = [];
            let index = event.currentTarget.dataset.index;
            let value = !that.data.list[index].interest;
            //console.log(value);
            let interestParam = {}, countParam = {};
            // let param = {};
            // param[key] = value;

            const params = {
                "activityId": that.data.list[index].activityId, //活动点ID
                "weixin": app.globalData.openid,  //用户ID
                "isInterest": value//是否收藏，true为收藏，false为取消收藏
            };


            util.collectRequest(params, function (isInterest, count) {
                // that.setData(param)
                let isInterestKey = 'list[' + index + '].interest';
                let isInterestValue = isInterest;
                let countKey = 'list[' + index + '].numberOfInterest';
                let countVal = count;
                interestParam[isInterestKey] = isInterestValue;
                countParam[countKey] = countVal;
                //console.log(isInterest, count);

                that.setData(interestParam);
                that.setData(countParam);

            });

        });
    },
    //热门
    switchFind: function () {
        wx.switchTab({
            url: '../find/find'
        })
    },
    //跳转到活动地点
    place: function () {
        wx.navigateTo({
            url: "../place/place?act=" + JSON.stringify(actyinfo)
        })
    },
    //搜索地址
    searchAddress: function () {
        wx.navigateTo({
            url: '../search/search',
            success: function (res) {
            },
            fail: function (res) {
            },
            complete: function (res) {
            },
        })
    },
    qsearch: function (e) {
        wx.navigateTo({
            url: '../result/result?keyword=' + e.currentTarget.dataset.word
        })
        //console.log(e.currentTarget.dataset.word)

    },
    //获取列表
    getList: function () {
        let that = this;
        mapCtx.getRegion({
            success: function (res) {
                var params = {
                    leftCorner: (res.southwest.longitude) + "," + (res.northeast.latitude),
                    rightCorner: (res.northeast.longitude) + "," + (res.southwest.latitude),
                    weixin: app.globalData.openid,
                    pageSize: 100
                }
                //获取活动点接口
                request("m/activityarea/list.json", params).then(function (data) {
                    var re = data.data.result;
                    var con;
                    for (var i = 0; i < re.length; i++) {
                        if (i == 10) {
                            break
                        }
                        if (re[i].activityVos[0]) {
                            con = re[i].activityVos[0].name

                        } else {
                            con = re[i].areaName
                        }

                        re[i].callout = {
                            content: con,
                            display: "ALWAYS",
                            padding: "5",
                            fontSize: 14
                        }


                    }
                    that.setData({
                        markers: re
                    });


                }).catch(function (err) {
                })
            }
        })
    },


    //用户登录
    login: function () {
        wx.showLoading({
            title: '加载中...',
            mask: true
        })
        var that = this;
        wx.login({
            success: function (res) {

                if (res.code) {
                    request("m/weixin/map.json", {
                        appid: "wxb25947b5e530b90d",
                        js_code: res.code,
                        grant_type: "authorization_code"
                    }).then(function (res) {
                        console.log(res)
                        app.globalData.openid = res.data.result.openid;
                        //登陆接口
                        request("weixin/logon.json", {
                            weixin: app.globalData.openid
                        }).then(function (res) {
                            //console.log('aaa', res);
                            app.globalData.header = res.data.sessionId;
                            if (res.data.result.mobile != null) {
                                app.globalData.phone = res.data.result.mobile;
                                app.globalData.login = true;
                            }
                            // console.log(app.globalData.phone);
                        })
                        wx.getLocation({
                            type: 'wgs84',
                            success: function (res) {
                                app.globalData.latitude = res.latitude;
                                app.globalData.longitude = res.longitude;
                                latitude = app.globalData.latitude;
                                longitude = app.globalData.longitude;
                                that.setData({
                                    latitude: latitude,
                                    longitude: longitude
                                }, function () {
                                    that.getList();
                                })


                            }
                        })


                        wx.hideLoading();
                    })


                } else {
                }
            }
        });
    },
    //视野发生变化时触发
    regionchange: function (e) {
        if (e.type == "end") {
            this.getList()
        }

    },

    //点击事件
    markclick: function (e) {
        var that = this;
        //console.log(e)
        var id = e.markerId;
        var markdata = that.data.markers;
        var cur;
        for (var i = 0; i < that.data.markers.length;i++){
            if (that.data.markers[i].id==id){
                cur = that.data.markers[i];
                break;
            }
        }
        //console.log("cur",cur)
        var activities = cur.activityVos;

        //console.log(activities)
       
        actyinfo = {
            actId: cur.activityAreaId,
            curlati: cur.latitude,
            curlongi: cur.longitude
        }
        that.showSearchInfo(cur);
        that.changeMarkerColor(markdata,id);
        //点击地点显示
        this.setData({
            list: activities,
            showList: true,
        });


        for (let i = 0; i < that.data.list.length; i++) {
            let collectObsBean = new collectUtil.CollectObsBean();
            // console.log(collectObsBean.Tag);
            collectObsBean.tag = collectUtil.Tag.index;
            collectObsBean.activityId = that.data.list[i].activityId;

            collectObsBean.callBack = function CallBack(result) {
                //更新列表点数据
                that.data.markers[id].activityVos[i]["interest"] = result[0];
                that.data.markers[id].activityVos[i]["numberOfInterest"] = result[1];
                //更新UI的数据
                that.data.list[i]["interest"] = result[0];
                that.data.list[i]["numberOfInterest"] = result[1];
                //TODO 改成局部更新
                that.setData(that.data);
            };
            collectUtil.addActivity(collectObsBean);
        }
    },
    //气泡事件
    callouttap: function (e) {
        this.markclick(e);
    },
    //标记点事件
    makertap: function (e) {
        this.markclick(e);
    },


    //获取用户信息
    getUserInfo: function () {
        if (app.globalData.userInfo) {
            this.setData({
                userInfo: app.globalData.userInfo,
                hasUserInfo: true
            })
        } else {
            // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
            // 所以此处加入 callback 以防止这种情况
            app.userInfoReadyCallback = res => {
                this.setData({
                    userInfo: res.userInfo,
                    hasUserInfo: true
                })
            }
        }

        wx.getUserInfo({
            success: function (res) {
                app.globalData.userInfo = res.userInfo;
                app.globalData.hasUserInfo = true;
            }
        });
    },
    controltap: function (e) {
        var that = this;
        if (e.controlId == 2) {
            that.setData({
                latitude: app.globalData.latitude,
                longitude: app.globalData.longitude
            }, function () {
                that.getList();
            })

        }
    },
    onLoad: function () {
        var that = this;
        mapCtx = wx.createMapContext("map");
        wx.getSystemInfo({
            success: function (res) {
                //console.log("plat",res);
                var offheight;
                if (res.brand == "iPhone") {
                    offheight = res.windowHeight - 190
                } else {
                    offheight = res.windowHeight - 230
                }


                that.setData({
                    controls: [{
                        id: 1,
                        iconPath: '../../images/home_map_center.png',
                        position: {
                            left: res.windowWidth / 2 - 20,
                            top: res.windowHeight / 2 - 100
                        }
                    }, {
                        id: 2,
                        iconPath: '../../images/home_position.png',
                        position: {
                            left: 20,
                            top: offheight,
                            height: 55,
                            width: 55
                        },
                        clickable: true
                    }]
                })
            }
        })


        that.getUserInfo();
        that.login();
    },

    showSearchInfo: function (data) {
        var that = this;
        that.setData({
            placeData: {
                title: data.areaName
            }
        });
    },
    changeMarkerColor: function (data, id) {
        var that = this;
        var markersTemp = [];
        for (var i = 0; i < data.length; i++) {
            if (i === id) {

            } else {

            }
            markersTemp[i] = data[i];
        }
        that.setData({
            markers: markersTemp
        });
    },
    onShareAppMessage: function () {

    }
})
